<?php

namespace app\admin\controller\basic;

use app\common\controller\Backend;
use think\Db;

/**
 * 对话列表
 */
class Subject extends Backend
{

    /**
     * @var \app\common\model\Subject
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Subject;
        $schoolList = Db::name("school")->select();
        // 如果查询结果为空，赋值为空数组
        $this->schoolList = is_array($schoolList)? $schoolList : [];
        $schooldata = [0 => __('None')];
        foreach ($this->schoolList as $k => &$v) {
            $schooldata[$v['id']] = $v['name'];
        }
        $this->view->assign('schooldata', $schooldata);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            // 获取请求参数
            $params = $this->request->param();

            // 查询数据（带分页）
            $list = $this->model
                ->with('school')
                ->order($params['sort'] ?? 'id', $params['order'] ?? 'desc')
                ->paginate([
                    'list_rows' => $params['limit'] ?? 10,
                    'page'      => ($params['offset'] / $params['limit'] + 1) ?? 1
                ]);
            // 返回标准JSON格式
            $result = [
                "total" => $list->total(),
                "rows"  => $list->items()
            ];

            return json($result);
        }

        // 非AJAX请求返回视图
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post('row/a');

            if(empty($data['subject']) || empty($data['school_id'])){
                $this->error('内容不能为空'); 
            }

            $schoolId = $data['school_id'] ?? 0;
            unset($data['school_id']);
            $row = $this->model->save($data);
            
            if ($row) {
                // 保存关联关系
                if ($schoolId) {
                    $this->model->school()->attach($schoolId);
                }
                $this->success('添加成功',$row);
            }else{
                $this->error('添加失败'); 
            }
        }

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post('row/a');
            if(empty($data['subject']) || empty($data['school_id'])){
                $this->error('内容不能为空');
            }

            $row = $this->model->get($ids);
            $schoolId = $data['school_id'] ?? 0;
            unset($data['school_id']);

            // 更新数据库
            $result = $row->save($data);
            if ($result !== false) {
                // 删除现有的关联数据
                $row->school()->detach(); // 先删除所有关联关系，或者根据需要删除特定条件的关联

                // 保存新的关联关系
                if ($schoolId) {
                    $row->school()->attach($schoolId);
                }
            }
            $this->success('编辑成功');

        }

        $row = $this->model->get($ids);
        $schoolSubject = Db::name("school_subject_relation")
            ->where('subject_id', $ids)
            ->value('school_id');
        
        $this->view->assign([
            'row' => $row,
            'schoolSubject' => $schoolSubject,
        ]); 
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function delete($ids = null){
        if ($ids) {
            $rows = $this->model->where('id', 'in', $ids)->delete();
            if ($rows) {
                Db::name('school_subject_relation')->where('subject_id', 'in', $ids)->delete();
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('请选择要删除的记录');
    }
}